var kanjilish_profiles = null; // copy of the profiles array in the main window

// Clones (=creates exact copy) of any object:
function kanjilish_clone(object)
{
    if (typeof(object) != "object") return object;

    var newObject = object.constructor();

    for (objectItem in object)
        newObject[objectItem] = kanjilish_clone(object[objectItem]);

	return newObject;
}

// Add new item to the profiles list:
function kanjilish_misc_addProfile(name)
{
  var list = document.getElementById("kanjilish_profiles");

  var item = document.createElement('listitem');
  var cell = document.createElement('listcell');

  cell.setAttribute('label', name);

  item.appendChild(cell);
  list.appendChild(item);

  return item;
}

// initializes Options dialog by cloning main profile array:
function kanjilish_loadData()
{
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);

  // reference to the main browser window:
  var browserWindow = wm.getMostRecentWindow("navigator:browser");

  var list = document.getElementById("kanjilish_profiles");

  // read values from browserWindow:
  kanjilish_profiles = kanjilish_clone(browserWindow.kanjilish.profiles);

  for(var i = 0; i < kanjilish_profiles.length; i++)
  {
    var item = kanjilish_misc_addProfile(kanjilish_profiles[i][0]);

	if(browserWindow.kanjilish.current == i) // current profile
	  list.selectItem(item);
  }

  var keys = document.getElementById("kanjilish-control-key");
  var lk = keys.firstChild.childNodes.length;

  for(i = 0; i < lk; i++)
  {
    var child = keys.firstChild.childNodes[i];

    if(child.getAttribute("label") == browserWindow.kanjilish.key)
	{
	  keys.selectedIndex = i;
	  break;
	}
  }

  var mods_original = browserWindow.kanjilish.mod.split(" ");

  var mods = document.getElementById("kanjilish-control-mod-1");
  switch(mods_original[0])
  {
    case "alt":
	  mods.selectedIndex = 1;
	  break;

    case "control":
	  mods.selectedIndex = 2;
	  break;

    case "shift":
	  mods.selectedIndex = 3;
	  break;

	default:
	  mods.selectedIndex = 0;
	  break;
  }

  var mods2 = document.getElementById("kanjilish-control-mod-2");
  if(!mods_original[1])
  {
    mods2.selectedIndex = 0;
  }
  else
  {
    switch(mods_original[1])
    {
      case "alt":
	    mods2.selectedIndex = 1;
	    break;

      case "control":
	    mods2.selectedIndex = 2;
	    break;

      case "shift":
	    mods2.selectedIndex = 3;
	    break;

	  default:
	    mods2.selectedIndex = 0;
	    break;
    }
  }
}

// Saving changes - clone profile array back to the main window:
function kanjilish_unloadData()
{
  var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"]
                     .getService(Components.interfaces.nsIWindowMediator);

  var browserWindow = wm.getMostRecentWindow("navigator:browser");

  var list = document.getElementById("kanjilish_profiles");

  browserWindow.kanjilish.profiles = kanjilish_clone(kanjilish_profiles);
  browserWindow.kanjilish.current = list.selectedIndex;

  var keys = document.getElementById("kanjilish-control-key");
  browserWindow.kanjilish.key = keys.selectedItem.getAttribute("label");

  var mods = document.getElementById("kanjilish-control-mod-1");
  var mods2 = document.getElementById("kanjilish-control-mod-2");

  mods = mods.selectedItem.getAttribute("label");
  mods = (mods == "none") ? "" : mods;

  mods2 = mods2.selectedItem.getAttribute("label");
  mods2 = (mods2 == "none") ? "" : mods2;

  browserWindow.kanjilish.mod = mods + ((mods.length && mods2.length) ? " " : "") + mods2;

  // update status-bar UI with the new data:
  browserWindow.kanjilish.update();
}

// Loads and parses XML file with the profile data.
// Procedure is mostly taken from the init() method of the global kanjilish object.
function kanjilish_addProfile()
{
  const nsIFilePicker = Components.interfaces.nsIFilePicker;

  // this calls the standard file open dialog:
  var fp = Components.classes["@mozilla.org/filepicker;1"].createInstance(Components.interfaces.nsIFilePicker);
  fp.init(window, "Add XML", nsIFilePicker.modeOpen);
  fp.appendFilters(nsIFilePicker.filterXML);

  var rv = fp.show();
  if(rv == nsIFilePicker.returnOK || rv == nsIFilePicker.returnReplace)
  {
    // file is chosen. Load it:
    var file = fp.file;

	// Unicode converter - for later use:
    var suniconvCID = "@mozilla.org/intl/scriptableunicodeconverter";
    var suniconvIID = Components.interfaces.nsIScriptableUnicodeConverter;

    var uniConv = Components.classes[suniconvCID].createInstance(suniconvIID);
    uniConv.charset = "UTF-8";

    // open an input stream from file
    var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                            .createInstance(Components.interfaces.nsIFileInputStream);
    istream.init(file, 0x01, 0444, 0);
    istream.QueryInterface(Components.interfaces.nsILineInputStream);

    // read lines into array
    var line = {}, lines = [], hasmore;
    do
    {
      hasmore = istream.readLine(line);
      lines.push(line.value); 
    }
    while(hasmore);

    istream.close();

    try
    {
	  // Load file:
      var xml = lines.join("");
      xml = xml.substring(xml.indexOf("<"), xml.length);

      var dom = (new DOMParser()).parseFromString(xml, "text/xml");
      var name = dom.documentElement.getAttribute("title");
	  if(!name)
	  {
		alert("Invalid file format!");
		return;
	  }

	  // check if already exists:
      var list = document.getElementById("kanjilish_profiles");
	  var count = list.getRowCount();
	  for(var i = 0; i < count; i++)
	  {
	    if(list.getItemAtIndex(i).firstChild.getAttribute("label") == name)
		{
		  alert("This data set already exists!");
		  return;
		}
	  }

	  // copy the file to an extension's directory:
      var id = "kanjilish@jay.starkey";

      var newfile = Components.classes["@mozilla.org/extensions/manager;1"]
                    .getService(Components.interfaces.nsIExtensionManager)
                    .getInstallLocation(id)
                    .getItemLocation(id);

	  file.copyTo(newfile, file.leafName);

	  // parse the XML tree:

      var index = kanjilish_profiles.length;

      kanjilish_profiles[index] = [name, []];

      var elements = dom.documentElement.childNodes;
      for(var j = 0; j < elements.length; j++)
      {
        var element = elements[j];
        kanjilish_profiles[index][1][j] = [element.getAttribute("key").toLowerCase(), element.getAttribute("kanji").split(";")];

        // convert chars to Unicode:
        var array = kanjilish_profiles[index][1][j][1];
        for(var k = 0; k < array.length; k++)
          array[k] = uniConv.ConvertToUnicode(array[k]);
      }

      // Loading complete. Sort the keys by length:
      kanjilish_profiles[index][1].sort(function(a, b)
      {
        if(a[0].length < b[0].length)
          return 1;

        if(a[0].length > b[0].length)
          return -1;

        return 0;
      });

	  kanjilish_misc_addProfile(name);
    }
	catch(error) { alert(error); }
  }
}

// remove the profile (and the appropriate XML file):
function kanjilish_removeProfile()
{
  var list = document.getElementById("kanjilish_profiles");
  var name = kanjilish_profiles[list.selectedIndex][0];

  kanjilish_profiles.splice(list.selectedIndex, 1);

  list.removeItemAt(list.selectedIndex);
  list.selectItem(list.getItemAtIndex(0));

  var id = "kanjilish@jay.starkey";

  var ext = Components.classes["@mozilla.org/extensions/manager;1"]
                    .getService(Components.interfaces.nsIExtensionManager)
                    .getInstallLocation(id)
                    .getItemLocation(id); 

  var entries = ext.directoryEntries;
  var files = [];

  while(entries.hasMoreElements())
  {
    var entry = entries.getNext();
    entry.QueryInterface(Components.interfaces.nsIFile);

    var l = entry.leafName.length;
    if(entry.leafName.substring(l - 4, l) == ".xml") files.push(entry);
  }

  for(var i = 0; i < files.length; i++)
  {
    var file = files[i];

    // open an input stream from file
    var istream = Components.classes["@mozilla.org/network/file-input-stream;1"]
                            .createInstance(Components.interfaces.nsIFileInputStream);
    istream.init(file, 0x01, 0444, 0);
    istream.QueryInterface(Components.interfaces.nsILineInputStream);

    // read lines into array
    var line = {}, lines = [], hasmore;
    do
    {
      hasmore = istream.readLine(line);
      lines.push(line.value); 
    }
    while(hasmore);

    istream.close();

    var xml = lines.join("");
    xml = xml.substring(xml.indexOf("title=\"") + 7, xml.indexOf("\">")); // we only need the title of the profile here

	if(xml == name)
	{
	  file.remove(false);
	  break;
	}
  }
}